package com.estore.network;

import com.estore.service.ProductService;
import com.estore.model.Product;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private final ProductService productService;

    public EStoreServer() {
        // 初始化
        this.productService = new ProductService();
    }

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.startServer(8888);
    }

    private void startServer(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器已启动，监听端口：" + port);

            // 无限循环等待客户端连接
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("新客户端连接：" + clientSocket.getInetAddress());

                // 处理客户端请求
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleClient(Socket clientSocket) {
        try (
                ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())
        ) {
            //读取客户端请求
            String request = (String) ois.readObject();
            System.out.println("收到请求：" + request);

            // 响应数据
            Object responseData = null;
            //根据请求调用业务逻辑
            if ("GET_ALL_PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                responseData = products;
            }else if ("FIND_PRODUCT_BY_ID".equals(request)) {
                // 读取商品ID
                String productId = (String) ois.readObject();
                System.out.println("正在查找商品，ID: " + productId);
                Product product = productService.findProductById(productId);
                responseData = product;
            }
            //向客户端写回数据
            oos.writeObject(responseData);
            oos.flush();
            System.out.println("响应已发送");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}